<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="等级名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入等级名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 240px">
          <el-option v-for="item in nursing_level_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['nursing:level:add']">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" prop="id" />
      <el-table-column label="等级名称" align="center" prop="name" />
      <el-table-column label="护理计划名称" align="center" prop="planName" />
      <el-table-column label="护理费用" align="center" prop="fee" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
            {{ scope.row.status == 1 ? "启用" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="等级说明" align="center" prop="description" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="200px" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['nursing:level:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['nursing:level:remove']">删除</el-button>
          <el-button link type="primary" :icon="scope.row.status == 1 ? 'Lock' : 'Unlock'"
            @click="handleEnable(scope.row)" v-hasPermi="['nursing:level:edit']">{{ scope.row.status == 1 ? '停用' :
              '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改护理等级对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入等级名称" />
        </el-form-item>
        <!-- 下拉框：选择名称，绑定ID -->
        <el-form-item label="护理计划" prop="lplanId">
          <el-select v-model="form.lplanId" placeholder="请选择护理计划" style="width: 100%">
            <el-option v-for="item in planList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="护理费用" prop="fee" :step="5">
          <el-input-number v-model="form.fee" label="护理费用" placeholder="请输入" :min="1" :max="1000" :step="5" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="item in nursing_level_status" :label="item.value" size="large">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="等级说明" prop="description">
          <el-input v-model="form.description" placeholder="请输入等级说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import { listLevel, getLevel, delLevel, addLevel, updateLevel } from "@/api/nursing/level";
import { listAllPlan } from "@/api/nursing/plan";
import { ElMessage, ElMessageBox } from 'element-plus';
// 获取组件实例
const { proxy } = getCurrentInstance();


// 护理计划下拉框选项（value:计划ID，label:计划名称）
const planList = ref([]);

// 加载护理计划列表（用于下拉框）
const loadNursingPlans = async () => {
  try {
    const response = await listAllPlan();
    if (response.code === 200 && response.data?.length) {
      planList.value = response.data.map(plan => ({
        value: Number(plan.id), // 强制转为数字类型（避免后端返回字符串ID）
        label: plan.planName // 显示名称，不参与提交
      }));
    }
  } catch (error) {
    console.error('获取护理计划列表失败：', error);
    ElMessage.error('加载护理计划失败，请重试');
  }
};



const options = ref([
  { value: 1, label: "启用" },
  { value: 0, label: "停用" }
]);
const { nursing_level_status } = proxy.useDict("nursing_level_status");

const levelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询护理等级列表 */
function getList() {
  loading.value = true;
  // 并行执行：获取护理等级列表 + 加载护理计划下拉数据
  Promise.all([
    listLevel(queryParams.value), // 主列表数据
    loadNursingPlans() // 下拉表单数据
  ]).then(([levelResponse]) => {
    // 处理主列表数据
    levelList.value = levelResponse.rows;
    total.value = levelResponse.total;
  }).catch(error => {
    console.error('数据加载失败：', error);
  }).finally(() => {
    loading.value = false; // 无论成功失败，关闭加载状态
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    lplanId: null,
    fee: null,
    status: null,
    description: null,
    remark: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("levelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加护理等级";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]; // 注意：ids.value是数组，取第一个元素
  getLevel(_id).then(response => {
    const levelData = response.data;
    form.value = levelData;
    form.value.status = form.value.status + "";
    form.value.lplanId = Number(levelData.lplanId); // 确保是数字
    open.value = true;
    title.value = "修改护理等级";
  });
}

// 在watch中添加日志，确认选择后lplanId是数字
watch(
  () => form.value.lplanId,
  (newVal) => {
    console.log("选中的护理计划ID：", newVal, typeof newVal); // 应是数字类型（number）
    if (newVal) {
      const matchedPlan = planList.value.find(plan => plan.value === newVal);
      form.value.planName = matchedPlan ? matchedPlan.label : '';
    } else {
      form.value.planName = '';
    }
  }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate(valid => {
    if (valid) {
      // 删除这行错误代码：form.value.lplanId = Number(form.value.planName);

      // 额外校验：检查 lplanId 是否为有效数字（下拉框选择后会自动赋值）
      if (isNaN(form.value.lplanId)) {
        ElMessage.error('请选择有效的护理计划');
        return;
      }

      if (form.value.id != null) {
        updateLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          loadNursingPlans();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除护理等级编号为"' + _ids + '"的数据项？').then(function () {
    return delLevel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}
// 停用启用
function handleEnable(row) {
  const status = row.status;
  const msg = status === 0 ? "启用" : "停用";
  const param = { id: row.id, status: status === 0 ? 1 : 0 };
  ElMessageBox.confirm(
    '确认要' + msg + '该项目吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '删除',
      type: '警告',
    }
  )
    .then(async () => {
      await updateLevel(param);
      getList();
      ElMessage.success(msg + "成功");
    })
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('nursing/level/export', {
    ...queryParams.value
  }, `level_${new Date().getTime()}.xlsx`)
}

getList();
</script>
